const express = require('express');
const router = express.Router();
const {
	cartListModel,
	activityCartListModel,
	cartInfoListModel,
	activityRuleModel
} = require('../model/cart')
const {
	couponInfoListModel
} = require('../model/cart')
// 普通购物车信息
router.get('/cartList', async (req, res) => {
	const data = await cartListModel.find()
	res.send({
		code: 200,
		msg: '获取成功',
		data
	})
});

/*
* 添加、修改商品到购物车，skuNum值+1为递增，-1则为递减.
*   skuId   - 商品skuId.
*   skuNum  - 商品数量.
*/
router.get('/addToCart/:skuId/:skuNum', async (req, res) => {
	await cartInfoListModel.create(req.params)
	res.send({
		code: 200,
		msg: '添加成功'
	})
});

/*
* 切换商品选中状态
*   skuId   - 商品skuId.
*   isChecked   - 商品选中状态，1为选中，0为未选中.
*/
router.get('/checkCart/:skuId/:isChecked', async (req, res) => {
	const { skuId, isChecked } = req.params
	const data = await cartInfoListModel.updateOne({ skuId }, { isChecked })
	res.send({
		code: 200,
		msg: 'skuId',
		data
	})
});

/*
* 切换指定商品选中状态
*   isChecked   - 商品选中状态，1为选中，0为未选中.
*   skuIdList   - 商品skuId列表.
*/
router.post('/batchCheckCart/:isChecked', async (req, res) => {
	const data = await cartInfoListModel.find({ ...req.body })
	res.send({
		code: 200,
		msg: '切换商品',
		data
	})
});

/*
* 切换所有商品选中状态
*   isChecked   - 商品选中状态，1为选中，0为未选中.
*/
router.get('/checkAllCart/:isChecked', async (req, res) => {
	const data = await cartInfoListModel.updateMany({}, { isChecked })
	res.send({
		code: 200,
		msg: 'isChecked',
		data
	})
});

/*
* 删除购物 车商品
*   skuId   - 商品skuId.
*/
router.delete('/deleteCart/:skuId', async (req, res) => {
	await cartInfoListModel.deleteOne({ skuId: req.params.skuId })
	res.send({
		code: 200,
		msg: 'skuId'
	})
});

// 获取带活动购物车对象
router.get('/activityCartList', async (req, res) => {
	const result = (await activityCartListModel.find())[0]
	const couponInfoList = await couponInfoListModel.find()
	const activityRule = await  activityRuleModel.find()
	const cartInfoList = await cartInfoListModel.find()
	const carInfoVoList = [
		{
			activityRule,
			cartInfoList
		}
	]
	res.send({
		code: 200,
		msg: '获取成功',
		data: {
			couponInfoList,
			carInfoVoList,
			activityReduceAmount: result.activityReduceAmount,
			couponReduceAmount: result.couponReduceAmount,
			originalTotalAmount: result.originalTotalAmount,
			totalAmount: result.totalAmount
		}
	})
});

module.exports = router;
